package com.xuan.selectcourse.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

//Security配置类
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    //Spring Security配置
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //自定义表单登录
        http.formLogin()
                .loginPage("/admin_login") //自定义登录页面
                .usernameParameter("username")  //用户名
                .passwordParameter("password")  //密码
                .loginProcessingUrl("/user/login")  //表单提交路径
                .successHandler(new MyLoginSuccessHandler()) //登录成功处理器
                .failureForwardUrl("/login_fail"); //登录失败页面

        //权限拦截配置
        http.authorizeRequests()
                .antMatchers("/user/login").permitAll() //登录不需要认证
                .antMatchers("/login_fail").permitAll()  //登录失败不需要认证
                .antMatchers("/admin_login").permitAll() //登录页面不需要认证
                .antMatchers("/checkCode*").permitAll()  //验证码不需要认证
                .antMatchers("/backstage/**").permitAll()   //静态资源放行
                .antMatchers("/**").authenticated();     //其余都需要认证

        //退出登录
        http.logout()
                .logoutUrl("/user/logout") //退出登录路径
                .logoutSuccessUrl("/admin_login")  //退出登录成功后跳转的页面
                .clearAuthentication(true)   //退出成功后清除认证信息
                .invalidateHttpSession(true); //退出成功后清除session

        http.addFilterBefore(new BeforeLoginFilter(), UsernamePasswordAuthenticationFilter.class);


        //关闭csrf防护
        http.csrf().disable();
        //开启跨域访问
        http.cors();
    }

    //密码加密器
    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}
